﻿Option Strict On

Imports KUeLib.Buchungen
Imports KUeDataLib.Services
Imports System.ComponentModel
Imports System.Globalization
Imports System.Windows.Forms
Imports System.Drawing

Namespace Formulare.Buchungen

    Public Class ImportBuchungenForm
        Inherits WeifenLuo.WinFormsUI.Docking.DockContent

        Private WithEvents _backgroundWorker As New BackgroundWorker

        Private Sub BtnOpenFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpenFile.Click
            Dim ofd As New OpenFileDialog

            ofd.Multiselect = False

            If ofd.ShowDialog() = Windows.Forms.DialogResult.OK Then
                If IO.File.Exists(ofd.FileName) Then
                    Me.tbImportFile.Text = ofd.FileName
                    Me.btnImport.Enabled = True
                End If
            End If

        End Sub

        Private Sub btnImport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImport.Click
            Dim added As Boolean
            Dim lvi As ListViewItem
            ' Try

            Dim locsv As List(Of CSVEintrag) = (New CSVEintragExporter()).GetCSVEinträge( _
                KUeLib.Utils.GetDataTable(tbImportFile.Text, CChar(";")), tbImportFile.Text)

            Dim lob As List(Of Buchung) = (New BuchungCreator()).CreateBuchungen(locsv)

            Dim ds As KUeLib.Data.ServiceDefinitions.BuchungenDataSerivce = KUeLib.Data.ServiceManager.GetInstance().GetBuchungenDataService()

            pbImportState.Maximum = lob.Count
            pbImportState.Value = 0

            For Each b As Buchung In lob

                added = False

                If Not ds.BuchungExists(b) Then
                    ds.InsertBuchung(b)
                    added = True
                End If


                If added Then
                    lvi = lvImported.Items.Add("Importiert")
                Else
                    lvi = lvImported.Items.Add("Übersprungen")
                    lvi.BackColor = Color.LightGray
                End If

                lvi.SubItems.Add(b.Buchungsdatum.ToShortDateString())

                lvi.SubItems.Add(b.Buchungstext)

                Dim ci As New CultureInfo("de-DE")
                lvi.SubItems.Add(b.Betrag.ToString("C", ci.NumberFormat))

                If b.Betrag >= 0 Then
                    lvi.ForeColor = Color.Green
                Else
                    lvi.ForeColor = Color.Red
                End If

                pbImportState.Value += 1

            Next

            lvImported.Enabled = True
            For i As Integer = 0 To lvImported.Columns.Count - 1 Step 1
                lvImported.Columns(i).Width = -1
            Next

            'Catch ex As Exception
            '    ExHandlerLib.ExceptionHandler.GetInstance().HandleException(ex)
            'End Try
        End Sub


    End Class

End Namespace